package com.atguigu.gmall.apigateway.filter;

import com.alibaba.fastjson.JSON;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Autowired
    @Qualifier("redis")
    private RedisTemplate redisTemplate;

    @Value("${authUrls.url}")
    private String[] allUrl;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       ServerHttpRequest request = exchange.getRequest();
       ServerHttpResponse response = exchange.getResponse();
       String path = request.getURI().getPath();
       if(antPathMatcher.match("/**/inner/**",path)){
            System.out.println("内部资源");
                return out(response,ResultCodeEnum.PERMISSION);
        }
        String userId = getUserId(request);
        if(antPathMatcher.match("/**/auth/**",path)){
            if(StringUtils.isEmpty(userId)){
                return out(response,ResultCodeEnum.LOGIN_AUTH);
            }
        }
        for(String url : allUrl ){
            if(path.indexOf(url)!=-1&&StringUtils.isEmpty(userId)){
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set(HttpHeaders.LOCATION,"http://passport.gmall.com/login.html?originUrl="+request.getURI().getRawSchemeSpecificPart());
                return response.setComplete();
            }
        }

       if(!StringUtils.isEmpty(userId)){
            request.mutate().header("userId",userId).build();
       }
       String userTempId = getUserTempId(request);
       if(!StringUtils.isEmpty(userTempId)){
           request.mutate().header("userTempId",userTempId).build();
       }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result<Object> result = Result.build(null,resultCodeEnum);
        byte[] bytes = JSON.toJSONString(result).getBytes();
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE,"application/json;charset=utf-8");
        return response.writeWith(Mono.just(wrap));
    }

    public String getUserId(ServerHttpRequest request){
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            HttpCookie httpCookie = request.getCookies().getFirst("token");
            if(httpCookie!=null){
                token = httpCookie.getValue();
            }
        }
        if(!StringUtils.isEmpty(token)){
            if(redisTemplate.hasKey("user:login:"+token)){
               return (String) redisTemplate.opsForValue().get("user:login:"+token);
            }
        }
        return null;
    }
    //获取用户临时Id
    public String getUserTempId(ServerHttpRequest request){
        String userTempId = request.getHeaders().getFirst("userTempId");
        if(StringUtils.isEmpty(userTempId)){
            HttpCookie httpCookie = request.getCookies().getFirst("userTempId");
            if(httpCookie!=null){
                userTempId = httpCookie.getValue();
            }
        }
        return userTempId;
    }
}
